<?php
namespace teach\components;

use yii\base\Component;

/**
 * 服务商退款操作
 * Class WeChatRefund
 * @package teach\components
 */
class WeChatRefund extends Component
{
    protected $appid;

    protected $mch_id;

    protected $key;

    protected $sub_appid;

    protected $sub_mch_id;

    protected $transaction_id;

    protected $out_refund_no;

    protected $total_fee;

    protected $refund_fee;

    public function __construct($appid, $mch_id, $key, $sub_mch_id, $transaction_id, $out_refund_no, $total_fee, $refund_fee)
    {
        parent::__construct();

        $this->appid = $appid;

        $this->mch_id = $mch_id;

        $this->sub_mch_id = $sub_mch_id;

        $this->transaction_id = $transaction_id;

        $this->out_refund_no = $out_refund_no;

        $this->total_fee = $total_fee;

        $this->refund_fee = $refund_fee;

        $this->key = $key;
    }

    public function refund()
    {
        return $this->apply();
    }

    public function apply()
    {
        $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
        $parameters = [
            'appid' => $this->appid,
            'mch_id' => $this->mch_id,
            'sub_mch_id' => $this->sub_mch_id,
            'nonce_str' => $this->createNonceStr(),
            'transaction_id' => $this->transaction_id,
            'out_refund_no' => $this->out_refund_no,
            'refund_fee' => floatval($this->refund_fee) * 100,
            'total_fee' => floatval($this->total_fee) * 100,
        ];
        $parameters['sign'] = $this->getSign($parameters);
        $xmlData = $this->arrayToXml($parameters);
        return $this->xmlToArray($this->postXmlCurl($url, $xmlData, 60));
    }

    private function createNonceStr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getSign($Obj)
    {
        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . $this->key;
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        return $result_;
    }

    private function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = "";
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    private function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $xml .= "<" . $key . ">" . $this->arrayToXml($val) . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    private function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring), true);
        return $val;
    }

    private function postXmlCurl($url, $vars, $second = 30, $aHeader = array())
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //cert 与 key 分别属于两个.pem文件
        //请确保您的libcurl版本是否支持双向认证，版本高于7.20.1，相当于发curl验证【当前文件所在目录/cert/wxpay/】下的两个pem证书文件。
        curl_setopt($ch, CURLOPT_SSLCERT, dirname(__FILE__) . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'apiclient_cert.pem'); //TODO 证书位置
        curl_setopt($ch, CURLOPT_SSLKEY, dirname(__FILE__) . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR  . 'apiclient_key.pem'); //TODO 证书位置
        //curl_setopt($ch,CURLOPT_CAINFO,dirname(__FILE__).DIRECTORY_SEPARATOR.
        //    'cert'.DIRECTORY_SEPARATOR.'rootca.pem');    //这个不需要，因为大部分的操作系统都已经内置了rootca.pem证书了，就是常见的CA证书。
        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
        $data = curl_exec($ch);
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }
}